package com.fs.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.mapper.CaptMapper;
import com.fs.pojo.Capt;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.image.BufferedImage;
import java.util.Date;

@Service
public class CaptServiceImpl extends ServiceImpl<CaptMapper, Capt> implements CaptService {
    @Autowired
    private CaptMapper captMapper;

    @Autowired
    private Producer producer;

    @Override
    @Transactional
    public BufferedImage getCaptcha(String uuid) {
        if(StrUtil.isBlank(uuid)){
            return null;
//            throw new Exception("uuid不能为空");
        }
        String code = producer.createText();

        //5分钟后过期
        Date date = new Date();
        Capt capt = new Capt(uuid, code, DateUtil.offsetMinute(date,5));

        try {
            captMapper.insert(capt);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        //删除5分钟过期的
        captMapper.delete(new QueryWrapper<Capt>().lt("expire_time",DateUtil.offsetMinute(date,-5)));

        return producer.createImage(code);
    }
}
